package com.soso.j.spider.service.impl;

import java.net.MalformedURLException;

import com.caucho.hessian.service.HessianService;
import com.soso.core.exception.GeneralExceptionHandler;
import com.soso.core.util.log.Logger;
import com.soso.core.util.other.JsonUtil;
import com.soso.crawl.hessian.api.ReadCrawlInfoApi;
import com.soso.crawl.hessian.view.CrawlInfoCacheBo;
import com.soso.spider.context.SpiderContext;
import com.soso.spider.memcache.item.CrawlInfoCacheItem;
import com.soso.spider.service.CrawlInfoService;

public class CrawlInfoServiceImpl implements CrawlInfoService{
	@Override
	public CrawlInfoCacheBo read(String md5Digest, String readInfoUrl) {
		CrawlInfoCacheItem crawlInfoCacheItem = (CrawlInfoCacheItem) SpiderContext.getInstance().getCommonCache().get(md5Digest, new CrawlInfoCacheItem());
		if (crawlInfoCacheItem.getValue() != null) {
			return (CrawlInfoCacheBo) crawlInfoCacheItem.getValue();
		}
		CrawlInfoCacheBo crawlInfoCacheBo = null;
		try{
			ReadCrawlInfoApi readApi = HessianService.call(ReadCrawlInfoApi.class, readInfoUrl);
			String jsonCrawlCacheBo = readApi.read(md5Digest);
			if (jsonCrawlCacheBo != null && !"".equals(jsonCrawlCacheBo)) {
				JsonUtil<CrawlInfoCacheBo> jsonUtil=new JsonUtil<CrawlInfoCacheBo>(){};
				try{
					crawlInfoCacheBo=jsonUtil.fromJsonToObject(jsonCrawlCacheBo);
				}catch(Exception e){
					Logger.error(e.getMessage());
				}
			}
		} catch (MalformedURLException e) {
			GeneralExceptionHandler.handle(e);
		}
		if (crawlInfoCacheBo != null) {
			SpiderContext.getInstance().getCommonCache().put(md5Digest, new CrawlInfoCacheItem(crawlInfoCacheBo));
		}
		return crawlInfoCacheBo;
	}

}
